import DictService from '~/service/module/system/dictdata';
import useApp from '@admin/_find/store/app';
import { Ref, onBeforeMount, ref } from 'vue';
import DictData from '@admin/entity/system/dictdata/DictData';
import { toPromise } from '@xuekl/cli-utils';

export const useDict = (dict: string) => {
    const dictService = new DictService()
    const appStore = useApp()
    const list: Ref<DictData[]> = ref([])
    let complete: (vals: DictData[]) => void
    const getDict = async () => {
        const res = await dictService.getDict({ dict })
        if (res.code === 200) {
            appStore.dictData[dict] = res.data
            list.value = res.data
            complete && complete(list.value)
        }
    }

    const loaded = (call: (vals: DictData[]) => void) => {
        complete = call
    }

    onBeforeMount(() => {
        if (!dict) {
            complete && complete([])
        } else {
            if (!appStore.dictData[dict]) {
                // 拦截同页面 出现相同字典，会调用多次的问题
                appStore.dictData[dict] = []
                getDict()
            } else {
                list.value = appStore.dictData[dict]
                if (!list.value.length) {
                    toPromise(() => appStore.dictData[dict]).then((vals) => {
                        list.value = vals
                        complete && complete(list.value)
                    })
                } else {
                    complete && complete(list.value)
                }
            }
        }
    })

    return {
        list,
        loaded
    }
}
